import controller.base
import datetime
import logging


class PhotoHandler(controller.base.AuthHandler):
    def post(self):
        photoUrl = self.get_body_para("photoUrl")
        coments = self.get_body_para("comments")
        patientId = self.get_body_para("patientId")
        tag = self.get_body_para("tag")
        mode = self.get_body_para("mode")
        position = self.get_body_para("position")
        status = self.get_body_para("status")
        createTime = self.get_body_para("createTime")

        if coments is None:
            coments = None
        if tag is None:
            tag = ""
        if mode is None:
            mode = ""
        if position is None:
            position = ""
        if status is None:
            status = ""
        if createTime is None:
            createTime = datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S")

        if photoUrl is None or patientId is None:
            self.rsp(7, msg="parameter error")
            return

        # sql = 'SELECT * FROM patients WHERE id = %s'
        # res = self.db.get(sql, patientId)
        #
        # if res is None:
        #     self.rsp(8, msg="patient not exist")
        #     return
        # if res['doctor'] != self.user["id"]:
        #     self.rsp(9, msg="not your patient")
        #     return

        sql = "INSERT INTO photos (doctorId,photoUrl,coments,patientId,tag,mode,position,shootingStatus,createTime)" \
              " VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        res = self.db.insert(sql, self.user["id"], photoUrl, coments, patientId, tag, mode, position, status,
                             createTime)
        data = {
            "photos": {
                    "id": res,
                    "photoUrl": photoUrl,
                    "comments": coments,
                    "patientId": patientId,
                    "tag": tag,
                    "mode": mode,
                    "position": position,
                    "status": status,
            }
        }
        self.rsp(code=0, data=data)

    def get(self):
        page = self.get_query_argument('page', default=None)
        patient_id = self.get_query_argument('patient', default=None)
        if page is not None:
            page = int(page)
        if (page is not None) and page <= 0:
            self.rsp(6, msg="page starts from 1")
            return
        sql = 'SELECT * FROM photos WHERE doctorId = %s order by id desc'

        if patient_id is not None:
            sql += ' AND patientId = '
            sql += patient_id
        res = self.db.query(sql, self.user["id"])
        if res is None:
            self.rsp(6, msg="no patient exist")
            return
        length = len(res)

        start = 0
        end = length
        hasMore = False
        if page is not None:
            start = 20 * (page - 1)
            end = 20 * page
            if start > (length - 1):
                self.rsp(6, msg="page out of range")
                return
            if end >= length:
                end = length
            else:
                hasMore = True
        photos = []
        for idx in range(start, end):
            photo = res[idx]
            photos.append({
                    "id": photo["id"],
                    "photoUrl": photo["photoUrl"],
                    "comments": photo["coments"],
                    "patientId": photo["patientId"],
                    "tag": photo["tag"],
                    "mode": photo["mode"],
                    "position": photo["position"],
                    "createTime": photo["createTime"].strftime("%Y/%m/%d"),
                    "status": photo["shootingStatus"],
                })
        data = {"photos": photos, "hasMore": hasMore}
        self.rsp(code=0, data=data)

    def put(self, photo_id):
        id = photo_id

        photoUrl = self.get_body_para("photoUrl")
        coments = self.get_body_para("comments")
        patientId = self.get_body_para("patientId")
        tag = self.get_body_para("tag")
        mode = self.get_body_para("mode")
        position = self.get_body_para("position")
        status = self.get_body_para("status")

        if coments is None:
            coments = None
        if tag is None:
            tag = ""
        if mode is None:
            mode = ""
        if position is None:
            position = ""
        if status is None:
            status = ""

        if photoUrl is None or patientId is None:
            self.rsp(7, msg="parameter error")
            return

        sql = 'SELECT * FROM photos WHERE id = %s'
        res = self.db.get(sql, id)
        if res is None:
            self.rsp(8, msg="photo not exist")
            return
        if res['doctorId'] != self.user["id"]:
            self.rsp(9, msg="not your photo")
            return

        sql = 'SELECT * FROM patients WHERE id = %s'
        res = self.db.get(sql, patientId)

        if res is None:
            self.rsp(8, msg="patient not exist")
            return
        if res['doctor'] != self.user["id"]:
            self.rsp(9, msg="not your patient")
            return

        sql = "INSERT INTO photos (doctorId,photoUrl,coments,patientId,tag,mode,position,shootingStatus,createTime)" \
              " VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"

        sql = "UPDATE photos SET photoUrl = %s, coments = %s, patientId = %s, tag = %s, mode = %s, position =%s," \
              "shootingStatus =%s WHERE id = %s"
        res = self.db.update(sql, photoUrl, coments, patientId, tag, mode, position, status, id)
        data = {
            "photos": {
                    "id": id,
                    "photoUrl": photoUrl,
                    "comments": coments,
                    "patientId": patientId,
                    "tag": tag,
                    "mode": mode,
                    "position": position,
                    "status": status,
            }
        }
        self.rsp(code=0, data=data)

    def delete(self, photo_id):
        id = photo_id

        sql = 'SELECT * FROM photos WHERE id = %s'
        res = self.db.get(sql, id)
        if res is None:
            self.rsp(8, msg="photo not exist")
            return
        if res['doctorId'] != self.user["id"]:
            self.rsp(9, msg="not your photo")
            return

        sql = 'DELETE FROM photos WHERE  id = %s'
        res = self.db.execute(sql, id)
        self.rsp(code=0)

